package framework.basedao;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate4.HibernateCallback;

import java.io.Serializable;
import java.util.List;

/**
 * Created by lliu on 2015/11/7.
 */
public class HibernateGenericDao<E, I extends Serializable> extends HibernateCrudDao<E, I> implements GenericDao<E, I> {


    @Override
    public List<E> query(String hql, Object[] params) {
        return this.query(hql, params, 0, -1);
    }


    @Override
    public long count(final String countSql, final Object[] params) {
        return this.getHibernateTemplate().execute(new HibernateCallback<Long>() {
            @Override
            public Long doInHibernate(Session session) throws HibernateException {
                Query query = session.createQuery(countSql);
                if (params != null) {
                    for (int i = 0; i < params.length; i++) {
                        query.setParameter(i, params[i]);
                    }
                }
                return (Long) query.iterate().next();
            }
        });
    }


    @Override
    public List<E> query(final String hql, final Object[] params, final int firstResult, final int maxResult) {
        return this.getHibernateTemplate().execute(new HibernateCallback<List<E>>() {
            @Override
            public List<E> doInHibernate(Session session) throws HibernateException {
                Query query = session.createQuery(hql);
                if (params != null) {
                    for (int i = 0; i < params.length; i++) {
                        query.setParameter(i, params[i]);
                    }
                }
                query.setFirstResult(firstResult);
                if (maxResult != -1L) {
                    query.setMaxResults(maxResult);
                }
                return query.list();
            }
        });
    }


}
